<template>
  <div>
    <el-dialog
      v-model="dialogVisibleFlag"
      :title="props.isShareEditor == '0' ? '股东添加' : '股东修改'"
      width="80%"
      @close="closeShareEditorDialog"
      :close-on-click-modal="false"
    >
      <el-form :model="listQueryData">
        <el-form-item label="搜索关键字" prop="keyword">
          <el-input
            class="!w-[300px]"
            v-model="listQueryData.keyword"
            placeholder="请输入企业名称或统一社会信用代码 "
            autocomplete="off"
            clearable
          />
          <div class="ml10">
            <el-button
              type="primary"
              :disabled="!listQueryData.keyword"
              @click="hanlderShareholderInfo"
              >一键录入股东信息</el-button
            >
          </div>
        </el-form-item>
      </el-form>
      <div v-if="isFlag">
        <el-form :inline="true" :model="formList" ref="formRef" :rules="rules">
          <div v-for="(item, index) in formList.list" :key="index">
            <el-row>
              <el-col :span="6">
                <el-form-item
                  label="人员"
                  :prop="`list[${index}].peo_id`"
                  :rules="rules.peo_id"
                >
                  <el-select
                    disabled
                    v-model="item.peo_id"
                    placeholder="请选择人员"
                  >
                    <el-option
                      v-for="item in optionsList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="出资比例"
                  :prop="`list[${index}].fund_ratio`"
                  :rules="rules.fund_ratio"
                >
                  <el-input
                    disabled
                    placeholder="请输入出资比例"
                    v-model="item.fund_ratio"
                    clearable
                    @change="
                      validateNumber(item.fund_ratio, index, item, 'fund_ratio')
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="认缴日期"
                  style="width: 240px"
                  :prop="`list[${index}].subscribe_time`"
                  :rules="rules.subscribe_time"
                >
                  <el-date-picker
                    disabled
                    style="width: 300px"
                    v-model="item.subscribe_time"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择企业成立时间"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="认缴金额(万元)"
                  :prop="`list[${index}].subscribe_money`"
                  :rules="rules.subscribe_money"
                >
                  <el-input
                    disabled
                    placeholder="请输入认缴出资金额(万元)
                "
                    v-model="item.subscribe_money"
                    clearable
                    @change="
                      validateNumber(
                        item.subscribe_money,
                        index,
                        item,
                        'subscribe_money'
                      )
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="实缴金额(万元)"
                  :prop="`list[${index}].practical_money`"
                  :rules="rules.practical_money"
                >
                  <el-input
                    disabled
                    placeholder="请输入实缴出资金额(万元)
                          "
                    v-model="item.practical_money"
                    clearable
                    @change="
                      validateNumber(
                        item.practical_money,
                        index,
                        item,
                        'practical_money'
                      )
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="持股比例"
                  :prop="`list[${index}].shareholding_ratio`"
                  :rules="rules.shareholding_ratio"
                >
                  <el-input
                    placeholder="请输入持股比例

                          "
                    v-model="item.shareholding_ratio"
                    clearable
                    @change="
                      validateNumber(
                        item.shareholding_ratio,
                        index,
                        item,
                        'shareholding_ratio'
                      )
                    "
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item
                  label="受益股份"
                  :prop="`list[${index}].shareholding_beneficial`"
                  :rules="rules.shareholding_beneficial"
                >
                  <el-input
                    placeholder="请输入终受益股份比例

                          "
                    v-model="item.shareholding_beneficial"
                    clearable
                    @change="
                      validateNumber(
                        item.shareholding_beneficial,
                        index,
                        item,
                        'shareholding_beneficial'
                      )
                    "
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="add-box">
            <el-button @click="addCompanyShareInsert" type="primary">
              提交
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { getSessionKey } from "@/utils/auth";
import Refresh from "@iconify-icons/ep/refresh";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import Search from "@iconify-icons/ep/search";
import Check from "@iconify-icons/ep/check";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { message } from "@/utils/message";
import { peopleInsert } from "@/api/personnelPage";
const disabled = ref(false);
const listQueryData = reactive({
  keyword: ""
});
import {
  peopleSelect,
  companyShareInsert,
  companyShareUpdate,
  companyInsert,
  gudong,
  gongsi,
  shareInsert
} from "@/api/companyList";
import {
  reactive,
  ref,
  inject,
  onMounted,
  defineProps,
  defineEmits,
  nextTick,
  defineExpose,
  watch
} from "vue";
import { fa } from "element-plus/es/locale";
import { json } from "stream/consumers";
import { List } from "echarts/core";
const isFlag = ref(false);
const gudongId = ref("");
const dialogVisibleFlag = ref(false);
const listQuery = ref({});
const listQueryRef = ref("");
const formRef = ref("");
const companyIdInfo = ref();
const props = defineProps({
  isShareEditor: {
    type: String,
    default: ""
  }
});
const rules = ref({
  peo_id: [{ required: true, message: "请选择人员", trigger: "blur" }]
  // fund_ratio: [{ required: true, message: "请输入出资比例", trigger: "blur" }],
  // subscribe_time: [
  //   { required: true, message: "请选择认缴出资日期", trigger: "blur" }
  // ],
  // subscribe_money: [
  //   { required: true, message: "请输入认缴出资金额", trigger: "blur" }
  // ],
  // practical_money: [
  //   { required: true, message: "请输入实缴出资金额", trigger: "blur" }
  // ],
  // shareholding_ratio: [
  //   { required: true, message: "请输入持股比例", trigger: "blur" }
  // ],
  // shareholding_beneficial: [
  //   { required: true, message: "最终受益股份比例", trigger: "blur" }
  // ]
});
onMounted(() => {
  getList();
});
// 添加
const hanlderShareholderInfo = () => {
  const params = {
    keyword: listQueryData.keyword
  };
  gudong(params).then(res => {
    console.log(res, "参数的哈哈哈哈哈好");
    if (res.code == 200) {
      isFlag.value = true;
      formList.value.list = res.data;
    } else {
      isFlag.value = false;
    }
  });
};
// 打开弹框
const openShareEditorDialog = companyId => {
  dialogVisibleFlag.value = true;
  console.log(companyId, "companyId哈哈哈");
  companyIdInfo.value = companyId;
  formList.value.list.map((el, i) => {
    el.company_id = companyId;
  });
};
// 关闭
const closeShareEditorDialog = () => {
  listQueryData.keyword = "";
  dialogVisibleFlag.value = false;
  isFlag.value = false;
  formList.value.list = [];
};
const getList = async () => {
  const obj = {
    name: ""
  };
  const res = await peopleSelect(obj);
  if (res.code == 200) {
    const dataList = res.data;
    optionsList.value = dataList;
  }
};
const handleDelete = index => {
  if (formList.value.list.length == 1) {
    message("暂无法删除", { type: "error" });
    return;
  }
  formList.value.list.splice(index, 1);
};
const optionsList = ref([]);
const formList = ref({
  list: [
    {
      people_id: "",
      fund_ratio: "",
      subscribe_time: "",
      subscribe_money: "",
      practical_money: "",
      shareholding_ratio: "",
      shareholding_beneficial: "",
      company_id: ""
    }
  ]
});
// 格式化
const validateNumber = (value, index, el, name) => {
  let newValue = value;
  const elInfo = JSON.parse(JSON.stringify(el));
  if (newValue) {
    newValue = newValue.toString();
    newValue = newValue.replace(/[^0-9.]/g, ""); ////清除"数字"和"."以外的字符
    newValue = newValue.replace(/^\./g, ""); //验证第一个字符是数字而不是点
    newValue = newValue.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的点
    newValue = newValue
      .replace(".", "$#$")
      .replace(/\./g, "")
      .replace("$#$", "."); //只保留第一个. 清除多余的点
    newValue = newValue.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
    newValue = Number(newValue);
    elInfo[name] = newValue;
    formList.value.list[index][name] = elInfo[name];
  }
};

// 编辑
const handleEdit = (item, i) => {
  formList.value.list.map((el, index) => {
    if (i == index) {
      el.isDisadled = false;
    }
  });
};
// 添加
const handleAdd = () => {
  formList.value.list.push({
    people_id: "",
    fund_ratio: "",
    subscribe_time: "",
    subscribe_money: "",
    practical_money: "",
    shareholding_ratio: "",
    shareholding_beneficial: "",
    company_id: ""
  });
};
// 股东保存提交按钮
const emit = defineEmits(["handleshareEditor"]);

const addCompanyShareInsert = () => {
  formRef.value.validate(valid => {
    if (valid) {
      const listArr = JSON.parse(JSON.stringify(formList.value.list));
      listArr.map(el => {
        console.log(el, "===-----====");
        if (el.peo_id.includes("公司") || el.peo_id.length > 4) {
          console.log(el.peo_id, "公司");
          getGoingsi(el.peo_id);
        } else {
          console.log(el.peo_id, "个人");
          getPeopleInsert(el.peo_id);
        }
      });

      setTimeout(() => {
        const itemData = JSON.parse(JSON.stringify(formList.value.list));
        console.log(itemData);
        const params = {
          action: "update",
          company_id: companyIdInfo.value,
          value: JSON.stringify(formList.value.list)
        };
        console.log(params, "itemData", formList.value.list);
        companyShareInsert(params).then(res => {
          if (res.code == 200) {
            message(res.msg, { type: "success" });
            closeShareEditorDialog();
            console.log("成功了");
            emit("handleshareEditor");
          }
        });
      }, 500);

      // console.log(formList.value.list);
      // const itemData = JSON.parse(JSON.stringify(formList.value.list));
      // const params = {
      //   value: JSON.stringify(itemData)
      // };
      // companyShareInsert(params).then(res => {
      //   console.log(res, "==---");
      //   if (res.code == 200) {
      //     dialogVisibleFlag.value = false;
      //     message(res.msg, { type: "success" });
      //     emit("handleshareEditor");
      //   }
      // });
      // console.log(itemData, value, "哈哈");
    } else {
      return false;
    }
  });
};

// 人员绑定
const getPeopleInsert = async name => {
  const obj = {
    admin_id: getSessionKey().admin_id,
    name,
    status: 1
  };
  const res = await peopleInsert(obj);
  const formListInfo = JSON.parse(JSON.stringify(formList.value.list));
  const infoList = [];
  formListInfo.filter(el => {
    if (el.peo_id == name) {
      el.peo_id = res.data;
      infoList.push({
        peo_id: name,
        id: res.data
      });
    }
    return el;
  });
  const arrData = infoList.map(el => {
    formList.value.list.map(item => {
      if (el.peo_id == item.peo_id) {
        item.peo_id = el.id;
        item.company_id = companyIdInfo.value;
        item.type = 1;
      }
    });
    return el;
  });
};

// 公司绑定
const getGoingsi = async keyword => {
  const params = {
    keyword
  };
  const resinfo = await gongsi(params);
  console.log(resinfo, "resinfo");
  const tax_code = resinfo.data.tax_code;
  // 人员添加
  const info = {
    admin_id: getSessionKey().admin_id,
    name: resinfo.data.legal,
    status: 1
  };
  const res = await peopleInsert(info);
  const obj = {
    name: keyword,
    ...resinfo.data,
    legal: res.data,
    admin_id: getSessionKey().admin_id
  };
  const res1 = await companyInsert(obj);
  const comId = res1.data;
  const formListInfoData = JSON.parse(JSON.stringify(formList.value.list));
  const arr = [];
  console.log("参数的", formListInfoData);
  formListInfoData.map(el => {
    if (el.peo_id.length > 3) {
      arr.push({
        peo_id: el.peo_id,
        comId
      });
    }
    return el;
  });
  arr.map(el => {
    formList.value.list.map(item => {
      if (el.peo_id == item.peo_id) {
        item.com_id = comId;
        item.type = 2;
        item.company_id = companyIdInfo.value;
        delete item.peo_id;
      }
    });
    return el;
  });
  // const inFo = JSON.parse(JSON.stringify(formList.value.list));
  // const params = {
  //   value: JSON.stringify(inFo)
  // };
  // shareInsert(params).then(res => {
  //   if (res.code == 200) {
  //     message(res.msg, { type: "success" });
  //     // closeShareEditorDialog();
  //   }
  // });
};

// 人员绑定
// const getPeopleInsert = name => {
//   const obj = {
//     admin_id: getSessionKey().admin_id,
//     name,
//     status: 1
//   };
//   peopleInsert(obj).then(res => {
//     const formListInfo = JSON.parse(JSON.stringify(formList.value.list));
//     const infoList = [];
//     formListInfo.filter(el => {
//       if (el.peo_id == name) {
//         el.peo_id = res.data;
//         infoList.push({
//           peo_id: name,
//           id: res.data
//         });
//       }
//       return el;
//     });
//     const arrData = infoList.map(el => {
//       formList.value.list.map(item => {
//         if (el.peo_id == item.peo_id) {
//           item.peo_id = el.id;
//           item.company_id = companyIdInfo.value;
//           item.type = 1;
//         }
//       });
//       return el;
//     });
//   });
// };

// // 公司绑定
// const getGoingsi = keyword => {
//   const params = {
//     keyword
//   };
//   gongsi(params).then(resinfo => {
//     console.log(resinfo);
//     const tax_code = resinfo.data.tax_code;
//     // 人员添加
//     const info = {
//       admin_id: getSessionKey().admin_id,
//       name: resinfo.data.legal,
//       status: 1
//     };
//     peopleInsert(info).then(res => {
//       const obj = {
//         name: keyword,
//         ...resinfo.data,
//         legal: res.data,
//         admin_id: getSessionKey().admin_id
//       };
//       companyInsert(obj).then(res => {
//         const comId = res.data;
//         const formListInfoData = JSON.parse(
//           JSON.stringify(formList.value.list)
//         );
//         const arr = [];
//         console.log("参数的", formListInfoData);
//         formListInfoData.map(el => {
//           if (el.peo_id.length > 3) {
//             arr.push({
//               peo_id: el.peo_id,
//               comId
//             });
//           }
//           return el;
//         });
//         arr.map(el => {
//           formList.value.list.map(item => {
//             if (el.peo_id == item.peo_id) {
//               item.com_id = comId;
//               item.type = 2;
//               item.company_id = companyIdInfo.value;
//               delete item.peo_id;
//             }
//           });
//           return el;
//         });
//         const inFo = JSON.parse(JSON.stringify(formList.value.list));
//         const params = {
//           value: JSON.stringify(inFo)
//         };
//         shareInsert(params).then(res => {
//           if (res.code == 200) {
//             message(res.msg, { type: "success" });
//             closeShareEditorDialog();
//           }
//         });
//       });
//     });
//   });
// };

defineExpose({ openShareEditorDialog, closeShareEditorDialog });

// const emit = defineEmits(["handleSubmit"]);
const handleSubmit = () => {
  listQueryRef.value.validate(valid => {
    if (valid) {
      // 添加
      const parmas = listQuery.value;
      // parmas.admin_id = getSessionKey().admin_id;
      emit("handleSubmit", parmas);
    }
  });
};
</script>

<style lang="scss" scoped>
.add-box {
  font-size: 30px;
}

.ml10 {
  margin-left: 10px;
}
</style>
